use bevy::prelude::*;
use bevy_asset_loader::prelude::*;

use crate::{ron::RonAssetPlugin, GameMaps, GameState};

pub struct LoadPlugin;

impl Plugin for LoadPlugin {
    fn build(&self, app: &mut App) {
        app.add_plugins(RonAssetPlugin::<GameMaps>::default())
            .add_loading_state(
                LoadingState::new(GameState::Loading)
                    .continue_to_state(GameState::LoadMap)
                    .with_dynamic_assets_file::<StandardDynamicAssetCollection>("load.assets.ron")
                    .load_collection::<GameSource>(),
            )
            .add_systems(OnEnter(GameState::LoadMap), setup_load_map)
            .add_systems(Update, load_map.run_if(in_state(GameState::LoadMap)));
    }
}
#[derive(Resource)]
struct HandleGameMaps(Handle<GameMaps>);

fn setup_load_map(mut commands: Commands, asset_server: Res<AssetServer>) {
    commands.insert_resource(HandleGameMaps(asset_server.load("map.ron")));
}

fn load_map(
    mut commands: Commands,
    map_handle: Res<HandleGameMaps>,
    mut maps: ResMut<Assets<GameMaps>>,
    mut next_state: ResMut<NextState<GameState>>,
) {
    if let Some(map) = maps.remove(map_handle.0.id()) {
        commands.insert_resource(map);
        next_state.set(GameState::Menu);
    }
}

#[derive(AssetCollection, Resource)]
pub struct GameSource {
    #[asset(key = "tank_layout")]
    pub tank_layout: Handle<TextureAtlasLayout>,
    #[asset(key = "tank_home")]
    pub tank_home: Handle<TextureAtlasLayout>,
    #[asset(key = "player0")]
    pub p0: Handle<Image>,
    #[asset(key = "player1")]
    pub p1: Handle<Image>,
    #[asset(key = "player2")]
    pub p2: Handle<Image>,
    #[asset(key = "player3")]
    pub p3: Handle<Image>,
    #[asset(key = "player4")]
    pub p4: Handle<Image>,
    #[asset(key = "player5")]
    pub p5: Handle<Image>,
    #[asset(key = "world")]
    pub world: Handle<Image>,
    #[asset(key = "logo")]
    pub logo: Handle<Image>,
    #[asset(key = "home")]
    pub home: Handle<Image>,
    #[asset(key = "blocks", collection(typed))]
    pub blocks: Vec<Handle<Image>>,
    #[asset(key = "font")]
    pub font: Handle<Font>,
    #[asset(key = "font_mono")]
    pub font_mono: Handle<Font>,
    #[asset(key = "font_icon")]
    pub font_icon: Handle<Font>,
    #[asset(key = "game_map")]
    pub game_map: Handle<Image>
}
